﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using kxcxw.Data;
using kxcxw.Data.Entities;
using System.Collections;
using System.Xml;
using System.Text.RegularExpressions;

namespace kxcxw.Data.Common
{
    public class CommonRepositories
    {
        string nodestring = "";
        public string getCategroyLine(string categoryId)
        {
            using (KXCXWDBContext db = new KXCXWDBContext())
            {
                var category = (from q in db.SysItemDetials
                                where q.ItemDeitalID == categoryId
                                select q).FirstOrDefault();
                nodestring = category.itemDetialName;
                getParentCategoryName(category.ItemDeitalPID);
                string[] nodearry = nodestring.Split(',');
                int length = nodearry.Length;
                string categoryLineStr = nodearry[length - 1];
                if (length > 1)
                {
                    for (int i = length - 2; i >= 0; i--)
                    {
                        categoryLineStr += "--" + nodearry[i];
                    }
                }
                return categoryLineStr;
            }
        }
        private void getParentCategoryName(string parentId)
        {
            using (KXCXWDBContext db = new KXCXWDBContext())
            {
                var category = (from q in db.SysItemDetials
                                where q.ItemDeitalID == parentId
                                select q).FirstOrDefault();
                if (category != null)
                {
                    nodestring += "," + category.itemDetialName;
                    getParentCategoryName(category.ItemDeitalPID);
                }
            }
        }
        private KXCXWDBContext db = new KXCXWDBContext();
        /// <summary>
        /// 公告列表
        /// </summary>
        /// <param name="typeId">公告类别ID</param>
        /// <returns></returns>
        public List<AnnouncementInfo> getAnnouncementList(string typeId)
        {
            List<AnnouncementInfo> list = (from q in db.AnnouncementInfoes
                                           where q.ItemID == typeId
                                           orderby q.CreateDate descending
                                           select q
                                             ).Take(10).ToList();
            return list;
        }

        /// <summary>
        /// 产品类别列表(显示到类别树上)
        /// </summary>
        /// <returns></returns>
        public List<SysItemDetial> getProductCategoryList()
        {
            List<SysItemDetial> list = (from q in db.SysItemDetials
                                        where q.ItemID == DataConstants.ProductTypeItemID
                                        orderby q.OrderID ascending
                                        select q).ToList();
            return list;
        }

        /// <summary>
        /// 大站导航列表(显示到类别树上)
        /// </summary>
        /// <returns></returns>
        public List<SysItemDetial> getWebSiteList()
        {
            List<SysItemDetial> list = (from q in db.SysItemDetials
                                        where q.ItemID == DataConstants.SourceTypeItemID && q.ItemDeitalID != "A445196E-75DE-4FF5-84F4-74176C629E9A"
                                        orderby q.OrderID ascending
                                        select q).ToList();
            return list;
        }

        /// <summary>
        /// 精品特色产品类别列表
        /// </summary>
        /// <param name="shoptype">网店 or 实体店</param>
        /// <param name="typeId">区域ID</param>
        /// <returns></returns>
        public List<PublichInformation> getAreaProductList(int shoptype, string typeid)
        {
            DateTime TempDate = DateTime.Now.AddDays(-DataConstants.ExpirationDay);
            List<PublichInformation> list = (from q in db.PublichInformations
                                             where q.AreaType == typeid   //暂时代替精品    q.EndDate < DateTime.Now &&
                                             && q.InfoType == shoptype
                                             && q.Status == DataConstants.Normal
                                             && ((q.EndDate == null && q.PublishDate >= TempDate) || q.EndDate >= DateTime.Now)
                                             select q).ToList();
            list = (list.OrderByDescending(p => p.PriorityLevel)
                            .ThenByDescending(p => p.TopDate)
                            .ThenByDescending(p => p.AlertDate)
                            .ThenByDescending(s => s.PublishDate)).Take(3).ToList();
            return list;
        }

        /// <summary>
        /// 跟据类别获取产品列表
        /// </summary>
        /// <param name="categoryId">类别id</param>
        /// <returns></returns>
        public IQueryable<PublichInformation> getProductListByCategory(string categoryId)
        {
            DateTime TempDate = DateTime.Now.AddDays(-DataConstants.ExpirationDay);
            IQueryable<PublichInformation> list = from q in db.PublichInformations
                                                  where q.ItemDeitalID == categoryId
                                                  && q.Status == DataConstants.Normal
                                                  select q;
            return list;
        }

        /// <summary>
        /// 跟据用户获取产品列表
        /// </summary>
        /// <param name="categoryId">类别id</param>
        /// <returns></returns>
        public IQueryable<PublichInformation> getProductListByUser(string UserId)
        {
            IQueryable<PublichInformation> list = from q in db.PublichInformations
                                                  where q.PublishID == UserId
                                                  orderby q.PriorityLevel descending
                                                  orderby q.TopDate descending
                                                  orderby q.AlertDate descending
                                                  orderby q.PublishDate descending
                                                  select q;
            return list;
        }

        /// <summary>
        /// 跟据字典表ID获取相应类别列表
        /// </summary>
        /// <param name="typeId">类别ID</param>
        /// <returns></returns>
        public List<SysItemDetial> getTypeListById(string typeId)
        {
            List<SysItemDetial> lstSysItemDetail = (from p in db.SysItemDetials
                                                    where p.ItemID.Equals(typeId)
                                                    orderby p.OrderID
                                                    select p).ToList<SysItemDetial>();
            return lstSysItemDetail;
        }

        /// <summary>
        /// 跟据字典表ID获取相应类别键值对列表
        /// </summary>
        /// <param name="typeId">类别ID</param>
        /// <returns></returns>
        public IEnumerable getTypeListByIdForDropDownList(string typeId)
        {
            IEnumerable sl = from c in db.SysItemDetials
                             where c.ItemID.Equals(typeId)
                             orderby c.OrderID
                             select new
                             {
                                 Name = c.itemDetialName,//值
                                 Id = c.ItemDeitalID,//健
                             };
            return sl;
        }

        /// <summary>
        /// 获取产品类别列表（根节点）
        /// </summary>
        /// <returns></returns>
        public IEnumerable getRootProductCategoryList()
        {
            IEnumerable sl = from c in db.SysItemDetials
                             where c.ItemID.Equals(DataConstants.ProductTypeItemID)
                             && c.ItemDeitalPID == null
                             orderby c.OrderID
                             select new
                             {
                                 Name = c.itemDetialName,//值
                                 Id = c.ItemDeitalID,//健
                             };
            return sl;
        }

        /// <summary>
        /// 根据上级类别ID获取下级类别列表
        /// </summary>
        /// <param name="typeId">类别ID</param>
        /// <returns></returns>
        public List<SysItemDetial> getProductCategoryListById(string categoryId)
        {
            List<SysItemDetial> sl = (from c in db.SysItemDetials
                                      where c.ItemDeitalPID.Equals(categoryId)
                                      orderby c.OrderID
                                      select c).ToList();
            return sl;
        }

        /// <summary>
        /// 根据id获取促销信息的对象
        /// </summary>
        /// <param name="infoId">信息ID</param>
        /// <returns></returns>
        public PublichInformation getInfoById(string infoId)
        {
            PublichInformation info = (from q in db.PublichInformations
                                       where q.InformationID == infoId
                                       select q).FirstOrDefault();
            return info;
        }

        public SysUserInfo getUserById(string userid)
        {
            SysUserInfo userinfo = (from q in db.SysUserInfoes
                                    where q.UserID == userid
                                    select q).FirstOrDefault();
            return userinfo;
        }

        /// <summary>
        /// 从图片的XML字段中删除指定名称的图片
        /// </summary>
        /// <param name="infoId">信息ID</param>
        /// <param name="filename">图片名称</param>
        /// <returns></returns>
        public bool DeleteimgDataById(string infoId, string filename)
        {
            PublichInformation info = getInfoById(infoId);
            string strImgs = info.PictureShow;
            if (strImgs != "")
            {
                XmlDocument xmlImgs = new XmlDocument();
                xmlImgs.LoadXml(strImgs);
                XmlNode root = xmlImgs.SelectSingleNode("imgs");
                foreach (XmlNode xn in root.ChildNodes)
                {
                    if (xn.InnerText == filename)
                    {
                        root.RemoveChild(xn);
                        info.PictureShow = xmlImgs.OuterXml;
                        db.SaveChanges();
                        return true;
                    }
                }
                return false;
            }
            return false;
        }

        public long getMiddleNumByHightestPrice(double HighestPrice)
        {
            long tempnum = Convert.ToInt64(HighestPrice) / 5;
            int templen = tempnum.ToString().Length;
            long mNum = 50;
            if (templen == 2)
            {
                if (100 - tempnum < tempnum - 50)
                    mNum = 100;
            }
            else if (templen > 2)
            {
                string tempstr = "1";
                for (int i = 1; i < templen; i++)
                    tempstr += "0";
                long minNum = Convert.ToInt64(tempstr);
                int maxWei = Convert.ToInt32(tempnum / minNum);
                mNum = maxWei * minNum;
            }
            return mNum;
        }

        public static string UrlReplace(string url, string parmeter, string value)
        {
            int index1 = url.IndexOf("?");
            if (index1 > 0)
            {
                string reg1 = ".*&" + parmeter + "=(.*)&";
                string reg2 = ".*&" + parmeter + "=(.*)";
                string reg3 = ".*\\?" + parmeter + "=(.*)";
                string value1 = Regex.Match(url, reg1).Groups[1].Value;
                string value2 = Regex.Match(url, reg2).Groups[1].Value;
                string value3 = Regex.Match(url, reg3).Groups[1].Value;
                string doneurl = "";
                if (value1 != "")
                {
                    doneurl = url.Replace(string.Format("&{0}={1}", parmeter, value1), string.Format("&{0}={1}", parmeter, value));
                }
                else if (value2 != "")
                {
                    doneurl = url.Replace(string.Format("&{0}={1}", parmeter, value2), string.Format("&{0}={1}", parmeter, value));
                }
                else if (value3 != "")
                {
                    doneurl = url.Replace(string.Format("?{0}={1}", parmeter, value3), string.Format("?{0}={1}", parmeter, value));
                }
                else
                {
                    doneurl = string.Format("{0}&{1}={2}", url, parmeter, value);
                }
                return doneurl;
            }
            else
            {
                url += string.Format("?{0}={1}", parmeter, value);
                return url;
            }
        }

        public bool isExistThisUrl(string url)
        {
            var info = (from q in db.PublichInformations
                        where q.ShopUrl == url
                        select q).FirstOrDefault();
            return (info != null);
        }
        /// <summary>
        /// 导购排行
        /// </summary>
        /// <param name="typeId"></param>
        /// <returns></returns>
        public List<Daogou> getDaoGouPopList(int? typeId)
        {
            var daogou = (from q in db.PublichInformations
                          from p in db.SysUserInfoes
                          where q.PublishID == p.UserID
                          && q.InfoType == typeId
                          group q by new
                          {
                              q.PublishID,
                              p.UserName
                          } into g
                          orderby g.Count() descending
                          select new Daogou
                          {
                              userId = g.Key.PublishID,
                              UserName = g.Key.UserName,
                              Count = g.Count()
                          }).Take(12);
            List<Daogou> daogoulist = daogou.ToList<Daogou>();
            return daogoulist;
        }

        public SysItemDetial getSysItemDetialbyId(string id)
        {
            var detail = (from q in db.SysItemDetials
                          where q.ItemDeitalID == id
                          select q).FirstOrDefault();
            return detail;
        }
    }
}